package com.engine.ch.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.engine.ch.action.WorkflowToPdfAction;
import com.engine.ch.entity.Archive;
import com.engine.ch.service.SyncArchive;
import com.engine.ch.util.OAFTPUploadUtil;
import com.engine.ch.util.OASFTPUploadUtil;
import com.engine.ch.util.ZipFileProcessor;
import com.google.common.base.Strings;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.NotNull;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SyncArchiveImpl implements SyncArchive {
    private static final Log log = LogFactory.getLog(SyncArchiveImpl.class);
    private static List<String> paths = new ArrayList<>();
    private static final String targetBasePath = "/data/datslscf";

    @Override
    public JSONObject sync(Archive archive) {
        // 组装请求参数
        JSONObject sendJson = new JSONObject();
        sendJson.put("username", "oa");  // 用户名
        sendJson.put("password", "9pXAbpSBfXHvrcv");  // 密码
        sendJson.put("channel", "oa"); // 系统来源通道
        sendJson.put("interfaceId", "oa_arch"); // 输入接口标识
        sendJson.put("debugMode", true); // 是否记录详细日志 true:开启 false:关闭（默认开启）
        JSONObject params = getJsonObject(archive);
        sendJson.put("param", params);
        log.info("请求参数：" + sendJson.toString());
//        String url ="http://172.30.136.201:8080/inter-system-api/archInterface/putData";
        String url = "http://172.30.136.201:18090/inter-system-api/archInterface/putData";
        String body = HttpRequest.post(url).header("Content-Type", "application/json").body(sendJson.toString()).execute().body();
        // 解析响应结果
        log.info("请求结果：" + body);
        JSONObject respJson = JSONObject.parseObject(body);
        String code = respJson.getString("code");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if ("200".equals(code)) {
            // 同步成功
            archive.setTsjg(0);
            archive.setTsjgsm(null);
            sdf.format(new Date());
            archive.setTssj(sdf.format(new Date()));
            // 同步成功，更新数据库
            RecordSet rs = new RecordSet();

            rs.executeUpdate("update uf_gwygdtsdaxtb set tsjg = ?, tsjgsm = ?, tssj = ? where lcrequestid = ?",
                    archive.getTsjg(), archive.getTsjgsm(), archive.getTssj(), archive.getLcrequestid());
        } else {
            // 同步失败
            archive.setTsjg(1);
            archive.setTsjgsm(respJson.getString("helpString"));
            archive.setTssj(sdf.format(new Date()));
            // 同步失败，更新数据库
            RecordSet rs = new RecordSet();
            rs.executeUpdate("update uf_gwygdtsdaxtb set tsjg = ?, tsjgsm = ?, tssj = ? where lcrequestid = ?",
                    archive.getTsjg(), archive.getTsjgsm(), archive.getTssj(), archive.getLcrequestid());
        }
        String requestId = archive.getLcrequestid();
        try {
            // 2. 调用一次，上传全部文件
            OASFTPUploadUtil.uploadFiles(paths, requestId);
        } catch (RuntimeException e) {
            log.error("批量上传失败", e);
            // 这里根据您的业务逻辑决定是继续还是回滚
        }

        // 3. 上传成功后，统一删除本地文件
        for (String path : paths) {
            if (!Strings.isNullOrEmpty(path)) {
                try {
                    ZipFileProcessor.deleteExtractedFolder(path);
                } catch (Exception e) {
                    log.error("删除本地文件时出错：" + path, e);
                }
            }
//        for (String path : paths) {
//            // 同步成功，删除本地文件
//            try {
//                OAFTPUploadUtil.uploadFile(path, requestId);
//            } catch (JSchException | SftpException e) {
//                throw new RuntimeException(e);
//            }
//            if (!Strings.isNullOrEmpty(path)) {
//                try {
//                    ZipFileProcessor.deleteExtractedFolder(path);
//                } catch (Exception e) {
//                    log.error("删除文件时出错：" + path, e);
//                }
//            }
        }
        return null;
    }

    @NotNull
    private static JSONObject getJsonObject(Archive archive) {
        JSONObject params = new JSONObject();
        params.put("sysBussId", archive.getLcrequestid()); // 流程id
        params.put("fileId", archive.getWjid()); // 数据id
        params.put("titleProper", archive.getBt()); // 标题
        String szbm = archive.getSzbm();
        if (!Strings.isNullOrEmpty(szbm)) {
            String sql = "select departmentname,departmentcode from hrmdepartment where id = " + szbm;
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql);
            if (rs.next()) {
                String departmentCode = rs.getString("departmentcode");
                if(Strings.isNullOrEmpty(departmentCode)){
                   szbm =  rs.getString("departmentname");
                }else {
                    szbm = departmentCode;
                }
            }
            params.put("szbm", szbm);
        } else {
            params.put("szbm", archive.getLwdw()); // 所属部门 发文：拟稿单位 收文：来文单位 1
        }
        params.put("fileCode", archive.getWjbhfwzh()); // 文件编号 发文：发文字号 收文：发文字号
        params.put("author", archive.getZrzgs()); // 责任者 发文：公司发文固定：四川航空股份有限公司 部门发文为拟稿单位 收文：来文单位
        String zrzbm = archive.getZrzbm();
        if (!Strings.isNullOrEmpty(zrzbm)) {
            String sql = "select departmentname from hrmdepartment where id = " + zrzbm;
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql);
            if (rs.next()) {
                zrzbm = rs.getString("departmentname");
            }
            params.put("author", zrzbm); // 责任者 发文：公司发文固定：四川航空股份有限公司 部门发文为拟稿单位 收文：来文单位 1
        } else {
            params.put("author", archive.getZrzgs()); // 责任者 发文：公司发文固定：四川航空股份有限公司 部门发文为拟稿单位 收文：来文单位
        }
        params.put("fileDate", archive.getCwrq()); // 成文日期
        params.put("pageCount", archive.getYs()); // 页数
        String mj = archive.getMj();
        if ("1".equals(mj) || "2".equals(mj)) {
            params.put("miji", "内部"); // 密级
        } else if ("3".equals(mj)) {
            params.put("miji", "公开"); // 密级
        } else {
            params.put("miji", "公开");
        }
        String ndhfwzh = archive.getNdhfwzh();
        if (!Strings.isNullOrEmpty(ndhfwzh)) {
            int start = ndhfwzh.indexOf('〔');
            int end = ndhfwzh.indexOf('〕');
            if (start != -1 && end != -1 && start < end) {
                String year = ndhfwzh.substring(start + 1, end);
                params.put("yearCode", year); // 年度号 发文：发文字号中的年度号 收文：发文字号中的年度号
            } else {
                log.error("年度号格式不正确：" + ndhfwzh);
            }
        } else {
            params.put("yearCode", archive.getNdhfwzh()); // 年度号 发文：发文字号中的年度号 收文：发文字号中的年度号
        }
        String bgqx = archive.getBgqx();
        if ("0".equals(bgqx)) {
            params.put("retentionPeriod", "10年"); // 保管期限
        } else if ("1".equals(bgqx)) {
            params.put("retentionPeriod", "30年");
        } else if ("2".equals(bgqx)) {
            params.put("retentionPeriod", "永久");
        }
        params.put("fwrq", archive.getFwrq()); //发文日期  发文 ：发文日期 收文：空
        params.put("swsj", archive.getSwsj()); // 收文日期 发文：空 收文：收文日期
        String sfwlx = archive.getSfwlx();  // 决议、决定、命令（令）、公报、公告、通告、意见、通知、通报、报告、请示、批复、议案、函、纪要、其他
        if ("0".equals(sfwlx)) {
            params.put("sfwlx", "收文"); //
        } else if ("1".equals(sfwlx)) {
            params.put("sfwlx", "行政类发文"); // 文种
        } else if ("2".equals(sfwlx)) {
            params.put("sfwlx", "政工类发文"); // 文种
        }
        params.put("zsdw", archive.getZsdw()); // 主送单位 发文：主送单位，多个单位逗号分隔 收文：空
        String zsdw = archive.getZsdw();
        if (!Strings.isNullOrEmpty(zsdw)) {
            String sql = "select departmentname from hrmdepartment where id in (" + zsdw + ")";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql);
            StringBuilder departmentNames = new StringBuilder();
            while (rs.next()) {
                if (departmentNames.length() > 0) {
                    departmentNames.append(",");
                }
                departmentNames.append(rs.getString("departmentname"));
            }
            if (departmentNames.length() > 0) {
                zsdw = departmentNames.toString();
            }else {
                zsdw = "";
            }
            params.put("zsdw", zsdw);// 主送单位 发文：主送单位，多个单位逗号分隔 收文：空
        }
        List<JSONObject> attrsLists = new ArrayList<>();
        String fj = archive.getFj();
        RecordSet rs = new RecordSet();
        String fileName = "";
        String imageFileId = "";
        Long fileSize = 0L;
        String TL_ARCH_FILEURL = "";
        Integer orderNo = 0;
        String MD5 = "";
        String docId = "";
        String ownerId = archive.getWjid();
        String sql = "";
        JSONObject js = new JSONObject();
        ImageFileManager imageFileManager = new ImageFileManager();
        String targetBasePathuse = targetBasePath + "/" + archive.getLcrequestid();
        String filePath = "";
        InputStream imagefile = null;
        File targetFile = null;
        File parentDir = null;
        if(!Strings.isNullOrEmpty(fj)) {
            sql = "SELECT id,IMAGEFILEID,VERSIONID,IMAGEFILENAME from docimagefile where docid = " + fj;
            rs.executeQuery(sql);
            if (rs.next()) {
                imageFileId = rs.getString("imagefileid");
                orderNo = rs.getInt("versionid");
                docId = rs.getString("id");
                fileName = rs.getString("imagefilename");
            }
            sql = "SELECT FILESIZE, FILEREALPATH  from  imagefile where IMAGEFILEID = " + imageFileId;
            rs.executeQuery(sql);
            if (rs.next()) {
                fileSize = Long.valueOf(rs.getString("FILESIZE") == null ? "0" : rs.getString("FILESIZE"));
                TL_ARCH_FILEURL = rs.getString("FILEREALPATH"); // 文件路径
            }
            js.put("docId", docId);
            js.put("ownerId", ownerId);
            js.put("fileName", fileName);
            js.put("fileFormat", getFileSuffix(fileName));
            js.put("fileSize", fileSize);
            filePath = targetBasePathuse + "/" + fileName;
            imageFileManager.getImageFileInfoById(Integer.parseInt(imageFileId));//imagefileid表示附件ID
            imagefile = imageFileManager.getInputStream();
            targetFile = new File(filePath);
            parentDir = targetFile.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                if (parentDir.mkdirs()) {
                    System.out.println("已创建目录: " + parentDir.getAbsolutePath());
                }
            }
            // 2. 使用try-with-resources确保流正确关闭
            try (OutputStream outputStream = new FileOutputStream(targetFile)) {
                byte[] buffer = new byte[8192]; // 8KB缓冲区
                int bytesRead;

                while ((bytesRead = imagefile.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // todo 生成imagefile
//        WorkflowToPdfAction workflowToDoc = new WorkflowToPdfAction();
//        long newFileSize = targetFile.length();
//        int i = workflowToDoc.saveImageFile(targetFile.getName(), filePath, newFileSize, true);
//        log.info("解压解密生成的附件id：["+i+"]");
//        if("doc".equals(getFileSuffix(fileName))|| "docx".equals(getFileSuffix(fileName))){// 文档转pdf
//            log.info("文档转pdf,imageFileId["+imageFileId+"]开始");
//            weaver.wps.doccenter.impl.ConvertDocToPdf ConvertDocToPdf= new weaver.wps.doccenter.impl.ConvertDocToPdf();
//            int newFileid=ConvertDocToPdf.ConvertToPDF(i,fileName,false);
//            log.info("文档转pdf生成文件id,newFileid["+newFileid+"]");
//            RecordSet recordSet = new RecordSet();
//            String fileSql ="select filerealpath from imagefile where imagefileid="+newFileid;
//            recordSet.executeQuery(fileSql);
//            if(recordSet.next()){
//                TL_ARCH_FILEURL = recordSet.getString("filerealpath"); // 文件路径
//            }else{
//                TL_ARCH_FILEURL = filePath;
//            }
//            log.info("文档转pdf,imageFileId["+imageFileId+"]结束,newFileid["+newFileid+"],TL_ARCH_FILEURL["+TL_ARCH_FILEURL+"]");
//        }
            log.info("解压文件后文件路径: " + filePath);
            paths.add(filePath);
            js.put("TL_ARCH_FILEURL", filePath);
            js.put("orderNo", orderNo);
            js.put("MD5", MD5);
            attrsLists.add(js);
        }
        // 正文
        log.info("正文处理开始 ");
        String zw = archive.getZw();
        sql = "SELECT id,IMAGEFILEID,VERSIONID,IMAGEFILENAME from docimagefile where docid = " + zw;
        rs.executeQuery(sql);
        if (rs.next()) {
            imageFileId = rs.getString("imagefileid");
            orderNo = rs.getInt("versionid");
            docId = rs.getString("id");
            fileName = rs.getString("imagefilename");
        }
        sql = "SELECT FILESIZE, FILEREALPATH from  imagefile where IMAGEFILEID = " + imageFileId;
        rs.executeQuery(sql);
        if (rs.next()) {
            fileSize = Long.valueOf(rs.getString("FILESIZE") == null ? "0" : rs.getString("FILESIZE"));
            TL_ARCH_FILEURL = rs.getString("FILEREALPATH"); // 文件路径
        }
        js = new JSONObject();
        js.put("docId", docId);
        js.put("ownerId", ownerId);
        js.put("fileName", fileName);
        js.put("fileFormat", getFileSuffix(fileName));
        js.put("fileSize", fileSize);
        filePath = targetBasePathuse + "/" + fileName;
        imageFileManager = new ImageFileManager();
        imageFileManager.getImageFileInfoById(Integer.parseInt(imageFileId));//imagefileid表示附件ID
        imagefile = imageFileManager.getInputStream();
        targetFile = new File(filePath);
        parentDir = targetFile.getParentFile();
        log.info("正文处理开始,filePath["+filePath+"]");
        log.info("正文处理开始,parentDir["+parentDir+"]");
        if (parentDir != null && !parentDir.exists()) {
            if (parentDir.mkdirs()) {
                System.out.println("已创建目录: " + parentDir.getAbsolutePath());
            }
        }
        // 2. 使用try-with-resources确保流正确关闭
        try (OutputStream outputStream = new FileOutputStream(targetFile)) {
            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int bytesRead;

            while ((bytesRead = imagefile.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        paths.add(filePath);
        log.info("解压后正文文件路径: " + filePath);
        js.put("TL_ARCH_FILEURL", filePath);
        js.put("orderNo", orderNo);
        js.put("MD5", MD5);
        attrsLists.add(js);
        // pdf 附件
        log.info("pdf 附件处理开始 ");
        String spjlsfwdpdf = archive.getSpjlsfwdpdf();
        sql = "SELECT id,IMAGEFILEID,VERSIONID,IMAGEFILENAME from docimagefile where docid = " + spjlsfwdpdf;
        rs.executeQuery(sql);
        if (rs.next()) {
            imageFileId = rs.getString("imagefileid");
            orderNo = rs.getInt("versionid");
            docId = rs.getString("id");
            fileName = rs.getString("imagefilename");
        }
        sql = "SELECT FILESIZE, FILEREALPATH from  imagefile where IMAGEFILEID = " + imageFileId;
        rs.executeQuery(sql);
        if (rs.next()) {
            fileSize = Long.valueOf(rs.getString("FILESIZE") == null ? "0" : rs.getString("FILESIZE"));
            TL_ARCH_FILEURL = rs.getString("FILEREALPATH"); // 文件路径
        }
        js = new JSONObject();
        js.put("docId", docId);
        js.put("ownerId", ownerId);
        js.put("fileName", fileName);
        js.put("fileFormat", getFileSuffix(fileName));
        js.put("fileSize", fileSize);
        filePath = TL_ARCH_FILEURL + "/" + fileName;
        paths.add(filePath);
        js.put("TL_ARCH_FILEURL", filePath);
        js.put("orderNo", orderNo);
        js.put("MD5", MD5);
        attrsLists.add(js);
        params.put("attrs", attrsLists); // 文件列表
        return params;
    }

    public static String getFileSuffix(String fileName) {
        // 参数校验
        if (fileName == null || fileName.trim().isEmpty()) {
            return "";
        }
        fileName = fileName.trim();
        // 查找最后一个点的位置
        int lastDotIndex = fileName.lastIndexOf(".");
        // 如果没有点，或者点在最后一位，返回空字符串
        if (lastDotIndex == -1 || lastDotIndex == fileName.length() - 1) {
            return "";
        }
        return fileName.substring(lastDotIndex + 1).toLowerCase();
    }
}
